import { Button, Modal, Popconfirm, Row, Space, Table } from "antd";
import React, { useEffect, useState } from "react";
import Config from "./config";
import axios from "axios";
import {
  DELETE_USER,
  DELETE_USER_BY_ID,
  GET_USER_LIST,
} from "../../../../constants/api-constants";
import { useBoolean } from "ahooks";
import Detail from "./detail";

export default () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<any>([]);
  const [dataSource, setDataSource] = useState<UserList.Item[]>();
  const [page, setPage] = useState(1);
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [role, setRole] = useState("all");
  const [loading, setLoading] = useState(false);
  const [count, setCount] = useState(0);
  const [states, setStates] = useState("all");
  const [
    isDetailShow,
    { setTrue: setDetailShow, setFalse: setDetailFalse },
  ] = useBoolean(false);
  const [record, setRecord] = useState<UserList.Item>();
  const [mainData, setMainData] = useState();
  useEffect(() => {
    setLoading(true);
    axios
      .get(GET_USER_LIST, {
        params: { page, phone, email, name, role, states },
      })
      .then((r) => {
        const { mainData } = r.data;
        setCount(mainData.count);
        setMainData(mainData);
        const dataSource = mainData.rows.map((v: any, _i: number) => {
          const {
            name,
            tel,
            email,
            age,
            organization,
            state,
            position,
            title,
            department,
            identity,
          } = v;
          return {
            defValue: v,
            key: v.id,
            name,
            tel,
            email,
            age,
            role: title?.name ?? "",
            fk_organization: organization?.name,
            state,
            post: position?.name ?? "",
            department,
            organizations: mainData.organizations,
            identity,
          };
        });
        setLoading(false);

        setDataSource([...dataSource]);
      })
      .catch((_r) => {
        console.log(_r);
        setLoading(false);
      });
  }, [page, phone, email, name, role, states]);

  const getList = () => {
    setLoading(true);
    axios
      .get(GET_USER_LIST, {
        params: { page, phone, email, name, role, states },
      })
      .then((r) => {
        const { mainData } = r.data;
        setCount(mainData.count);
        setMainData(mainData);
        const dataSource = mainData.rows.map((v: any, _i: number) => {
          const {
            name,
            tel,
            email,
            age,
            organization,
            state,
            position,
            title,
            department,
            identity,
          } = v;
          return {
            defValue: v,
            key: v.id,
            name,
            tel,
            email,
            age,
            role: title?.name ?? "",
            fk_organization: organization?.name,
            state,
            post: position?.name ?? "",
            department,
            organizations: mainData?.organizations,
            identity,
          };
        });
        setLoading(false);

        setDataSource([...dataSource]);
      })
      .catch((_r) => {
        console.log(_r);
        setLoading(false);
      });
  };

  let columns = [
    {
      title: "手机号",
      dataIndex: "tel",
      key: "tel",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "邮箱",
      dataIndex: "email",

      key: "email",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "用户姓名",
      dataIndex: "name",
      key: "name",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "用户角色",
      dataIndex: "identity",
      key: "identity",
      render: (text: number) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text === 0 ? "普通管理员" : "超级管理员"}
          </span>
        );
      },
    },
    {
      title: (
        <span
          style={{
            wordBreak: "break-all",
            width: "auto",
            display: "block",
            whiteSpace: "pre-wrap",
          }}
        >
          所属机构
        </span>
      ),
      dataIndex: "department",
      key: "department",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "职称",
      dataIndex: "role",
      key: "role",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "职务",
      dataIndex: "post",
      key: "post",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "用户状态",
      dataIndex: "state",
      key: "state",
      render: (text: number) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text === 0 ? "未审核" : text === 1 ? "已通过" : "冻结"}
          </span>
        );
      },
    },
    {
      title: "操作",
      render: (_value: any, record: any) => {
        return (
          <>
            <Space size={10}>
              {record.state === 1 ? (
                <Button
                  style={{ padding: 0, color: "#faad14" }}
                  onClick={() => {
                    const { key } = record;

                    axios
                      .post(DELETE_USER_BY_ID, { id: key, state: 3 })
                      .finally(() => {
                        getList();
                      });
                  }}
                  type={"link"}
                >
                  冻结
                </Button>
              ) : record.state === 2 ? (
                <Button
                  style={{ padding: 0, color: "#1890ff" }}
                  onClick={() => {
                    const { key } = record;

                    axios
                      .post(DELETE_USER_BY_ID, { id: key, state: 2 })
                      .finally(() => {
                        getList();
                      });
                  }}
                  type={"link"}
                >
                  解冻
                </Button>
              ) : (
                <Button
                  style={{ padding: 0, color: "#52c41a" }}
                  onClick={() => {
                    const { key } = record;

                    axios
                      .post(DELETE_USER_BY_ID, { id: key, state: 2 })
                      .finally(() => {
                        getList();
                      });
                  }}
                  type={"link"}
                >
                  通过
                </Button>
              )}

              <Popconfirm
                title="确认进行此操作?一经确认将无法取消"
                onConfirm={() => {
                  const { key } = record;

                  axios
                    .post(DELETE_USER_BY_ID, { id: key, state: 1 })
                    .finally(() => {
                      getList();
                    });
                }}
                okText="确定"
                cancelText="取消"
              >
                <Button style={{ padding: 0 }} type={"link"} danger>
                  删除
                </Button>
              </Popconfirm>
              {/* <Button
                style={{ padding: 0 }}
                onClick={() => {
                  setDetailShow();
                  setRecord(record);
                }}
                type={"link"}
              >
                详情
              </Button> */}
            </Space>
          </>
        );
      },
    },
  ];

  if (window.localStorage.getItem("identity") === null) {
    columns = columns.filter((column) => {
      return column.title !== "操作";
    });
  }

  return (
    <>
      <Config
        getList={getList}
        mainData={mainData}
        setDetailShow={setDetailShow}
        setRecord={setRecord}
        setRole={setRole}
        setStates={setStates}
        setName={setName}
        setEmail={setEmail}
        setPhone={setPhone}
        setPage={setPage}
      />
      <Table
        scroll={{ x: "60vw" }}
        pagination={{
          current: page,
          showSizeChanger: false,
          pageSize: 10,
          total: count,
          onChange: (page, _pageSize) => {
            setLoading(true);
            setPage(page);
            setLoading(false);
          },
        }}
        loading={loading}
        size={"middle"}
        rowSelection={{
          selectedRowKeys,
          onChange: (value) => {
            setSelectedRowKeys(value);
          },
          selections: [],
        }}
        columns={columns}
        dataSource={dataSource}
        footer={() => {
          return (
            <>
              {window.localStorage.getItem("identity") === null ? null : (
                <Row justify="space-between">
                  <Space>
                    <Space>
                      <Popconfirm
                        title="确定删除?一经删除将无法恢复"
                        onConfirm={() => {
                          const keys = selectedRowKeys.map((v: number) => {
                            if (dataSource) {
                              return v;
                            } else {
                              return 0;
                            }
                          });
                          axios
                            .post(DELETE_USER, {
                              id: keys,
                            })
                            .then((_r) => {
                              getList();
                            })
                            .catch((_r) => {
                              getList();
                            });
                        }}
                        okText="确定"
                        cancelText="取消"
                      >
                        <Button onClick={() => {}}>批量删除</Button>
                      </Popconfirm>
                    </Space>
                  </Space>
                </Row>
              )}
            </>
          );
        }}
      />

      <Modal
        title={record?.defValue ? "用户详情" : "增加用户"}
        visible={isDetailShow}
        onCancel={setDetailFalse}
        width={"80vw"}
        footer={null}
        destroyOnClose
      >
        <Detail
          getList={getList}
          setDetailFalse={setDetailFalse}
          record={record}
        />
      </Modal>
    </>
  );
};
